package com.example.ssss.ui.home;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.ssss.DeviceActivity;
import com.example.ssss.HistoryDetailActivity;
import com.example.ssss.R;
import com.example.ssss.data.MysqlOperation;
import com.example.ssss.data.entity.ShareData;
import com.example.ssss.databinding.FragmentHomeBinding;
import com.example.ssss.entity.HistoryInfo;
import com.example.ssss.entity.HistoryResponse;
import com.example.ssss.state.HomeStateViewModel;

import org.apache.iotdb.tsfile.read.filter.operator.In;

import java.util.Arrays;

public class HomeFragment extends Fragment {

//    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;
    private ImageView deviceAddBtn;
//    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
//    private String userid=preferences.getString("userId","10000");
    private String userid;


    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
//        homeViewModel =
//                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();
        HomeStateViewModel homeStateViewModel = new ViewModelProvider(getActivity()).get(HomeStateViewModel.class);
        userid = homeStateViewModel.getUserId();
        //final TextView textView = binding.textHome;
        /*homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                //textView.setText(s);
            }
        });*/
//        ListView mListView = binding.historyList;
        // 添加ListItem，设置事件响应
        select();
//        mListView.setAdapter(new HistoryListAdapter());
//        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            public void onItemClick(AdapterView<?> arg0, View v, int index,
//                                    long arg3) {
//                onListItemClick(index);
//            }
//        });

        deviceAddBtn=binding.deviceAddBtn;
        deviceAddBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                intent = new Intent(getActivity(), DeviceActivity.class);
                getActivity().startActivity(intent);
            }
        });

        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    void onListItemClick(int index) {
        Intent intent = null;
        intent = new Intent(getActivity(), HistoryDetailActivity.class);
        intent.putExtra("index",index+"");
        intent.putExtra("date",demos[index].getDate());
        this.startActivity(intent);
    }

    private static HistoryInfo[] demos = {
            new HistoryInfo("2022.3.16","好","95", "245km","3h36m"),
            new HistoryInfo("2022.3.14","好","95", "245km","3h36m"),
            new HistoryInfo("2022.3.12","好","95", "245km","3h36m")
    };

    private class HistoryListAdapter extends BaseAdapter {
        public HistoryListAdapter() {
            super();
        }
        @Override
        public View getView(int index, View convertView, ViewGroup parent) {
            convertView = View.inflate(getActivity(), R.layout.history_list_item, null);
            TextView date = (TextView) convertView.findViewById(R.id.history_item_date);
            TextView score = (TextView) convertView.findViewById(R.id.history_item_score);
            TextView status = (TextView) convertView.findViewById(R.id.history_item_status);
            TextView distance = (TextView) convertView.findViewById(R.id.history_item_distance);
            TextView time = (TextView) convertView.findViewById(R.id.history_item_time);

            date.setText(demos[index].getDate());
            score.setText(demos[index].getScore());
            status.setText(demos[index].getStatus());
            distance.setText(demos[index].getDistance());
            time.setText(demos[index].getTime());
            System.out.println(demos[index].getDate()+"****************************************************************");
            return convertView;
        }

        @Override
        public int getCount() {
            if(demos==null)return 0;
            return demos.length;
        }

        @Override
        public Object getItem(int index) {
            return demos[index];
        }

        @Override
        public long getItemId(int id) {
            return id;
        }
    }

    @SuppressWarnings("HandlerLeak")
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg){
            demos= (HistoryInfo[]) msg.obj;
            ListView mListView = binding.historyList;
            System.out.println(Arrays.toString(demos));
            mListView.setAdapter(new HistoryListAdapter());
            mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> arg0, View v, int index,
                                        long arg3) {
                    onListItemClick(index);
                }
            });
        }
    };
    public void select(){
        new Thread(){
            @Override
            public void run() {
                super.run();
                MysqlOperation sql = new MysqlOperation();
                sql.historyDao=new MysqlOperation.HistoryDao();
                try {
//                    demos =sql.historyDao.select("history_item");
                    demos =sql.historyDao.select(userid);
                    System.out.println("Mysql连接成功");
                    Message message=new Message();
                    message.obj=demos;
                    handler.sendMessage(message);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }.start();
    }
}